package com.server.modules.api.web;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.server.common.utils.*;
import com.server.modules.api.Base.BaseAppController;
import com.server.modules.api.entity.dayu.Results;
import com.server.modules.api.utils.Constants;
import com.server.modules.api.utils.ObjcetCopy;
import com.server.modules.api.vo.*;
import com.server.modules.sys.entity.User;
import com.server.modules.sys.entity.material.MaterialUpload;
import com.server.modules.sys.entity.member.Member;
import com.server.modules.sys.entity.tag.Tag;
import com.server.modules.sys.entity.valicode.ValiCode;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 用户接口
 * Created by wanglei on 2016/7/20.
 */
@Controller
@RequestMapping(value = "/api/member")
public class MemberAPIController extends BaseAppController {
	private Random random = new Random();
	//注册错误拦截
	private Map<String, TreeSet<Date>> registErrorMap = new HashMap<String, TreeSet<Date>>();
	//登录错误拦截
	private Map<String, TreeSet<Date>> loginErrorMap = new HashMap<String, TreeSet<Date>>();

	@ResponseBody
	@RequestMapping(value = "/getValiCode")
	public ValiCodeVo getValiCode(HttpServletRequest request, String telephone) {
		ValiCodeVo<ValiCode> vo = new ValiCodeVo<ValiCode>();
		if (StringUtils.isEmpty(telephone)) {
			vo.setRetCode(100);
			vo.setRetMsg("手机号码获取失败");
			return vo;
		}
		telephone = telephone.trim();
		//拦截
		//同一个手机号1分钟内只允许发送一次，同一天内只允许发送20次，同一个IP地址1分钟内只允许发送5条短信
		List<ValiCode> telList = valiCodeAPIService.selectValiCodeByTelephone(telephone);//获取最近的20条

		long now = System.currentTimeMillis();

		if (telList.size() == 0) {
			//说明此手机号还未发送过验证码，需要判断IP
			judgeIp(telephone, request, vo, now, telList);
		} else if (telList.size() >= 1 && now - telList.get(0).getSentTime().getTime() < 60 * 1000) {
			//同一号码一分钟之内已经发送了一次，不再允许此次发送
			vo.setRetCode(100);
			vo.setRetMsg("同一号码在1分钟之内最多只能发送1次");
		} else if (telList.size() >= 20 && now - telList.get(telList.size() - 1).getSentTime().getTime() < 24 * 60 * 60 * 1000) {
			//同一号码一天之内发送了20次，则不再允许此次发送
			vo.setRetCode(100);
			vo.setRetMsg("同一号码在1天之内最多只能发送20次");
		} else {
			//判断IP
			judgeIp(telephone, request, vo, now, telList);
		}
		return vo;
	}

	/**
	 * 判断IP
	 *
	 * @param telephone
	 * @param request
	 * @param vo
	 * @param now
	 * @param telList
	 */
	private void judgeIp(String telephone, HttpServletRequest request, ValiCodeVo vo, long now, List<ValiCode> telList) {
		List<ValiCode> ipList = valiCodeAPIService.selectValiCodeByIp(IPUtils.getIpAddr(request));//获取最近的5条
		if (ipList.size() == 0) {
			//说明此IP也未发送过验证码
			send(telephone, request, vo);
		} else if (ipList.size() >= 5 && now - ipList.get(ipList.size() - 1).getSentTime().getTime() < 60 * 1000) {
			//说明是同一IP在1分钟之内请求了5次，这里不允许发送
			vo.setRetCode(100);
			vo.setRetMsg("同一IP在1分钟之内最多只能发送5次");
		} else {
			//可以发送
			send(telephone, request, vo);
		}
	}

	/**
	 * 发送验证码
	 *
	 * @param telephone
	 * @param request
	 * @param vo
	 */
	private void send(String telephone, HttpServletRequest request, ValiCodeVo vo) {
		String url = "http://gw.api.taobao.com/router/rest";
		String appKey = "23422674";
		String secret = "9e6613eaf8816c6078ce68f69ba2ffde";
		String code = createValiCode();
		TaobaoClient client = new DefaultTaobaoClient(url, appKey, secret);
		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		req.setExtend("123456");
		req.setSmsType("normal");
		req.setSmsFreeSignName("贷贷帮");//短信签名名称
		req.setSmsParamString("{'code':'" + code + "','product':'贷贷帮'}");
		req.setRecNum(telephone);
		req.setSmsTemplateCode("SMS_29925139");
		try {
			AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);

			Results res = new Gson().fromJson(rsp.getBody(), Results.class);

			//获取结果中的错误码
			String errCode = res.alibaba_aliqin_fc_sms_num_send_response.result.err_code;

			if ("0".equals(errCode)) {
				//说明验证码发送成功
				ValiCode valiCode = new ValiCode();
				valiCode.setId(IdGen.uuid());
				valiCode.setTelephone(telephone);
				valiCode.setClientIp(IPUtils.getIpAddr(request));
				valiCode.setSentCode(code);
				valiCode.setSentTime(new Date());
				valiCode.setId(IdGen.uuid());
				valiCode.setIsNewRecord(true);
				valiCodeAPIService.insertValiCode(valiCode);
				vo.setRetCode(0);
				vo.setRetMsg("验证码发送成功");
				//vo.setData(valiCode);
			} else {
				vo.setRetCode(120);
				vo.setRetMsg("验证码发送失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			vo.setRetCode(120);
			vo.setRetMsg("验证码发送失败");
		}
	}

	@ResponseBody
	@RequestMapping(value = "/regist", method = RequestMethod.POST)
	public MemberVo regist(HttpServletRequest request, Member member) {
		MemberVo<Member> vo = new MemberVo<Member>();
		String telephone = member.getTelephone();
		String sentCode = request.getParameter("valiCode");
		String refereePhone = request.getParameter("refereePhone");
		//先拦截判断，1分钟内最多允许验证码输错4次
		TreeSet<Date> errorSet = registErrorMap.get(telephone);

		//先把一分钟以前的记录删除
		if (errorSet != null) {
			Iterator<Date> it = errorSet.iterator();
			if (it != null) {
				while (it.hasNext()) {
					if (System.currentTimeMillis() - it.next().getTime() > 60 * 1000) {
						it.remove();
					} else {
						break;
					}
				}
			}

			//判断拦截
			if (errorSet.size() >= 4 && System.currentTimeMillis() - errorSet.first().getTime() < 60 * 1000) {
				vo.setRetCode(100);
				vo.setRetMsg("一分钟内最多允许输错4次，请稍候再试");
				return vo;
			}
		}

		if (StringUtils.isEmpty(telephone) || StringUtils.isEmpty(member.getPassword()) || StringUtils.isEmpty(member.getDeviceType()) || StringUtils.isEmpty(member.getDeviceId()) || StringUtils.isEmpty(member.getVersion())) {
			vo.setRetCode(100);
			vo.setRetMsg("注册信息不能为空");
			return vo;
		}

		//检查是否已经注册
		Member existMember = memberAPIService.selectMemberByTelephone(telephone);

		if (existMember != null) {
			vo.setRetCode(100);
			vo.setRetMsg("该号码已被注册");
			return vo;
		}
		List<String> userList = new ArrayList<String>(1);
		//检查号码与验证码是否匹配
		ValiCode rightValiCode = valiCodeAPIService.selectLastValiCode(telephone, sentCode);
		if (rightValiCode == null) {
			//将错误信息记录到registErrorMap中
			TreeSet<Date> set = null;
			if (registErrorMap.containsKey(telephone)) {
				set = registErrorMap.get(telephone);
			} else {
				set = new TreeSet<Date>();
			}
			set.add(new Date());
			registErrorMap.put(telephone, set);

			//剩余机会
			int remainTimes = 4;
			if (registErrorMap.containsKey(telephone)) {
				remainTimes -= registErrorMap.get(telephone).size();
			}

			vo.setRetCode(100);
			if (remainTimes > 0) {
				vo.setRetMsg("验证码错误，您还有" + remainTimes + "次机会");
			} else {
				vo.setRetMsg("1分钟内错误次数太多，请稍候再试");
			}

			return vo;
		} else if (System.currentTimeMillis() - rightValiCode.getSentTime().getTime() > 2 * 60 * 1000) {
			//验证码超时
			vo.setRetCode(100);
			vo.setRetMsg("验证码超时，请重新发送");
			return vo;
		}

		//设置ID个用户
		member.setId(IdGen.uuid());

		member.setUsername(telephone);
		if (StringUtils.isNotEmpty(refereePhone)){
			User user = userAPIService.getUserByPhoneNum(refereePhone);
			if (user ==null){
				user = userAPIService.getUserById("1");
			}
			//member.setCreateBy(user);
			//12/01修改：为商务人员多加了个字段  和createby区分开
			member.setManagerId(user.getId());
			userList.add(user.getHxUsername());
		}else{
			//散户
			User user  = userAPIService.getUserById("1");
			member.setManagerId(user.getId());
			userList.add(user.getHxUsername());
		}
		//设置环信用户名和密码

		try {
			member.setHxUsername(UUIDUtils.getUUID() );
			member.setHxPassword(MD5Utils.md5Encode(member.getHxUsername()));
		}catch (Exception e){
			logger.error(e.getMessage());
		}

		member.setCreateDate(new Date());
		member.setCreateIp(IPUtils.getIpAddr(request));
		//先将登录信息设置给当前用户，如果注册成功就接着登录
		member.setLoginTime(new Date());
		member.setLoginIp(IPUtils.getIpAddr(request));
		//不是经理
		member.setIsManager(0);

		//登录操作，内部实现注册成功后自动登录
		member = memberAPIService.insertMember(member);

		if (member == null) {
			vo.setRetCode(120);
			vo.setRetMsg("注册失败");
		} else {
			imService.createNewIMUserSingle(member.getHxUsername(),member.getHxPassword(),member.getTelephone());
			vo.setRetCode(0);
			vo.setRetMsg("注册并登录成功");
			vo.setData(member);
		}
		Map<String,String > msg = new HashedMap();
		msg.put("type","text");
		msg.put("msg","你推荐的用户电话号码为:"+member.getTelephone()+"的用户已成功注册");
		imService.addFriendSingle(member.getHxUsername(),userList.get(0));

		imService.sendSysMessages(userList,msg,null);
		return vo;
	}

	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public MemberVo login(HttpServletRequest request, Member member) {
		MemberVo<Member> vo = new MemberVo<Member>();
		//判断数据有效性
		if (StringUtils.isEmpty(member.getTelephone()) || StringUtils.isEmpty(member.getPassword()) || StringUtils.isEmpty(member.getDeviceType()) || StringUtils.isEmpty(member.getDeviceId()) || StringUtils.isEmpty(member.getVersion())) {
			vo.setRetCode(100);
			vo.setRetMsg("参数错误");
			return vo;
		}
		//先做登录错误拦截
		TreeSet<Date> errorSet = null;
		if (!StringUtils.isEmpty(member.getTelephone())) {
			errorSet = loginErrorMap.get(member.getTelephone());
		}

		if (errorSet != null) {
			//先把一分钟以前的记录删除
			Iterator<Date> it = errorSet.iterator();
			if (it != null) {
				while (it.hasNext()) {
					if (System.currentTimeMillis() - it.next().getTime() > 60 * 1000) {
						it.remove();
					} else {
						break;
					}
				}
			}

			//判断拦截
			if (errorSet.size() >= 6 && System.currentTimeMillis() - errorSet.first().getTime() < 60 * 1000) {
				vo.setRetCode(100);
				vo.setRetMsg("一分钟内最多允许登录6次，请稍候再试");
				return vo;
			}
		}

		member.setLoginTime(new Date());
		member.setLoginIp(IPUtils.getIpAddr(request));

		Member result = memberAPIService.setlectMemberForLogin(member);
		//如果验证失败
		if (result == null) {
			vo.setRetCode(120);

			//先把错误记录到记录集中
			TreeSet<Date> set = null;
			if (!StringUtils.isEmpty(member.getTelephone())) {
				if (loginErrorMap.containsKey(member.getTelephone())) {
					set = loginErrorMap.get(member.getTelephone());
				} else {
					set = new TreeSet<Date>();
				}
				set.add(new Date());
				loginErrorMap.put(member.getTelephone(), set);
			}

			//再计算剩余机会
			int remainTimes = 6;
			if (loginErrorMap.containsKey(member.getTelephone())) {
				remainTimes -= loginErrorMap.get(member.getTelephone()).size();
			}
			if (remainTimes > 0) {
				vo.setRetMsg("手机号码或密码错误，您还有" + remainTimes + "次机会");
			} else {
				vo.setRetMsg("登录错误次数过于频繁，请稍候再试");
			}
		} else {
			CustomMemberVO customMemberVO = new CustomMemberVO();
			MemberVo memberVo = new MemberVo();
			MemberVo memberVo1 = new MemberVo();
			result.setPassword(null);
			ObjcetCopy.copyPropertiesIgnoreNull(result,memberVo);
			if (StringUtils.isNotEmpty(result.getOpenId())){
				result.setOpenId("1");
			}else {
				memberVo.setOpenId("0");
			}
			if (StringUtils.isNotEmpty(memberVo.getUnionId())){
				memberVo.setUnionId("1");
			}else {
				memberVo.setUnionId("0");
			}
			customMemberVO.setMember(memberVo);
			List<Tag> listTag =  tagAPIService.selectTagsByMember(result);
			if (listTag != null){
				customMemberVO.setTags(listTag);
			}

			memberVo1.setRetMsg("登录成功");
			memberVo1.setRetCode(0);
			memberVo1.setData(customMemberVO);
			return memberVo1;
		}
		return vo;
	}

	@ResponseBody
	@RequestMapping(value = "/loginByQq", method = RequestMethod.POST)
	public MemberVo loginByQq(HttpServletRequest request, Member member) {
//		String accessToken = request.getParameter("accessToken");
//		String openId = request.getParameter("openId");
//		String nickname = request.getParameter("nickname");
//		String province = request.getParameter("province");
//		String city = request.getParameter("city");
//		String face = request.getParameter("face");
//		String deviceType = request.getParameter("deviceType");
//		String deviceId = request.getParameter("deviceId");
//		String version = request.getParameter("version");

		MemberVo<Member> vo = new MemberVo<Member>();

		if (StringUtils.isEmpty(member.getAccessToken()) || StringUtils.isEmpty(member.getOpenId()) || StringUtils.isEmpty(member.getDeviceType()) || StringUtils.isEmpty(member.getDeviceId()) || StringUtils.isEmpty(member.getVersion())) {
			vo.setRetCode(100);
			vo.setRetMsg("参数错误");
			return vo;
		}

		//检查用户是否存在（按OpenID检查），并更新用户登录信息
		member.setLoginTime(new Date());
		member.setLoginIp(IPUtils.getIpAddr(request));
		Member result = memberAPIService.selectMemberByOpenId(member);

		if (result != null) {
			//说明存在
			vo.setRetCode(0);
			vo.setRetMsg("登录成功");
			vo.setData(result);
		} else {
			vo.setRetCode(120);
			vo.setRetMsg("用户未注册或者未绑定QQ，请先绑定");
		}

		return vo;
	}

	@ResponseBody
	@RequestMapping(value = "/loginByWx", method = RequestMethod.POST)
	public BaseQueryVo loginByWx(HttpServletRequest request, Member in_member) {
		BaseQueryVo vo = new BaseQueryVo();

		if (StringUtils.isEmpty(in_member.getAccessToken()) || StringUtils.isEmpty(in_member.getOpenId()) || StringUtils.isEmpty(in_member.getDeviceType()) ||
				StringUtils.isEmpty(in_member.getDeviceId()) || StringUtils.isEmpty(in_member.getVersion())) {
			vo.setRetCode(100);
			vo.setRetMsg("参数错误");
			return vo;
		}

		try {
			//先检查用户信息是否存在
			Member wxMember = wxService.getUserInfo(in_member.getAccessToken(), in_member.getOpenId());
			if (wxMember != null) {
				//说明微信用户信息获取成功
				//接下来就查询用户信息是否保存在数据库（主要是检测电话号码是否存在）

				//更新用户登录信息
				//由于UnionId是唯一的，所以微信的openId就不保存到数据库了，留该字段用来保存QQ的唯一openId
//				member.setOpenId(openId);
				wxMember.setAccessToken(in_member.getAccessToken());
				wxMember.setUnionId(in_member.getOpenId());
				wxMember.setLoginTime(new Date());
				wxMember.setLoginIp(IPUtils.getIpAddr(request));
				wxMember.setDeviceId(in_member.getDeviceId());
				wxMember.setDeviceType(in_member.getDeviceId());
				wxMember.setVersion(in_member.getVersion());
				CustomMemberVO customMemberVO = new CustomMemberVO();
				MemberVo memberVo = new MemberVo();
				MemberVo memberVo1 = new MemberVo();
				Member member = memberAPIService.selectMemberByUnionId(wxMember);
				if (member != null){
					vo.setRetCode(0);
					vo.setRetMsg("登录成功");
					ObjcetCopy.copyPropertiesIgnoreNull(member,memberVo);
					if (StringUtils.isNotEmpty(memberVo.getOpenId())){
						memberVo.setOpenId("1");
					}else {
						memberVo.setOpenId("0");
					}
					if (StringUtils.isNotEmpty(memberVo.getUnionId())){
						memberVo.setUnionId("1");
					}else {
						memberVo.setUnionId("0");
					}
					customMemberVO.setMember(memberVo);


					List<Tag> listTag =  tagAPIService.selectTagsByMember(member);
					if (listTag != null){
						customMemberVO.setTags(listTag);
					}
					vo.setData(customMemberVO);
				}else {
					vo.setRetCode(124);
					vo.setRetMsg("未注册或者未绑定微信，请先绑定");
					//也将用户信息返回客户端
					vo.setData(member);
				}
			}
		} catch (Exception e) {
			vo.setRetCode(120);
			vo.setRetMsg("用户信息获取失败");
			logger.error(e.getMessage());
		}
		return vo;
	}
	@ResponseBody
	@RequestMapping(value = "/checkSession", method = RequestMethod.POST)
	public MemberVo checkSession(HttpServletRequest request, String sessionId) {
		MemberVo vo = new MemberVo();

		if (StringUtils.isEmpty(sessionId)) {
			vo.setRetCode(120);
			vo.setRetMsg("需要重新登录");
			return vo;
		}

		Member member = memberAPIService.selectMemberBySessionId(sessionId);
		if (member == null) {
			vo.setRetCode(120);
			vo.setRetMsg("需要重新登录");
		} else {
			vo.setRetCode(0);
			vo.setRetMsg("已登录");
			vo.setData(member);
			if (!com.server.common.utils.StringUtils.isEmpty(member.getSessionId())){
				JedisUtils.set(member.getId(),member.getSessionId(),0);
			}
		}
		return vo;
	}

	/**
	 * 生成验证码
	 *
	 * @return
	 */
	public String createValiCode() {
		StringBuffer sb = new StringBuffer();
		while (sb.length() < 6) {
			sb.append(random.nextInt(10) + 1);
		}
		return sb.toString();
	}
	@ResponseBody
	@RequestMapping(value = "/updateAvatar", method = RequestMethod.POST)
	public  BaseQueryVo updateAvatar(HttpServletRequest request, FileVO vo) throws Exception{
		BaseQueryVo<MaterialUpload> rvo = new BaseQueryVo<MaterialUpload>();
		MaterialUpload materialUpload = null;
		if (!checkLogin(vo)){
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		materialUpload = materialUploadService.findMaterialUploadbymd5(MD5Utils.md5Encode(vo.getImageHash()));
		if (materialUpload != null && materialUpload.getUrl()!=null){
			Member member = memberAPIService.selectMemberById(vo.getMemberId());
			member.setFace(PathUtils.getImageURL()+materialUpload.getUrl());
			memberAPIService.save(member);
			materialUpload.setUrl(member.getFace());
			rvo.setRetCode(0);
			rvo.setRetMsg("文件已存在，不需要上传");
			rvo.setData(materialUpload);
			return rvo;
		}else{
			materialUpload =  new MaterialUpload();
			vo.setMemberId(vo.getMemberId());
			vo.setOrder("1");//单张照片排名第一
			vo.setTypeId("1");//头像
			User userBy = new User();
			userBy.setId("1");
			vo.setMd5(MD5Utils.md5Encode(vo.getImageHash()));
			userBy.setCreateDate(new Date());
			vo.setUserBy(userBy);
			String filePath = fileService.uploadFile(vo); //保存文件
			if (StringUtils.isEmpty(filePath)){
				return  returnMsgAPIService.getRet(Constants.saveError);
			}
			Member member = memberAPIService.selectMemberById(vo.getMemberId());
			member.setFace(PathUtils.getImageURL()+filePath);
			memberAPIService.save(member);
			materialUpload.setUrl(member.getFace());
			rvo.setData(materialUpload);
			return  rvo;
		}
	}
	@ResponseBody
	@RequestMapping(value = "/checkUploadAvatar", method = RequestMethod.POST)
	public  BaseQueryVo checkUploadAvatar(HttpServletRequest request, FileVO vo) throws Exception{
		BaseQueryVo<MaterialUpload> rvo = new BaseQueryVo<MaterialUpload>();
		MaterialUpload materialUpload = new MaterialUpload();
		if (!checkLogin(vo)){
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		materialUpload = materialUploadService.findMaterialUploadbymd5(vo.getMd5());
		if (materialUpload != null && materialUpload.getUrl()!=null){
			Member member = memberAPIService.selectMemberById(vo.getMemberId());
			member.setFace(PathUtils.getImageURL()+materialUpload.getUrl());
			memberAPIService.save(member);
			materialUpload.setUrl(member.getFace());
			rvo.setRetCode(0);
			rvo.setRetMsg("文件已存在，不需要上传");
			rvo.setData(materialUpload);
		}else{
			return  returnMsgAPIService.getRet(Constants.notFoundFile);
		}
		return  rvo;
	}
	@ResponseBody
	@RequestMapping(value = "/save" , method = RequestMethod.POST)
	public BaseQueryVo save(HttpServletRequest request,MemberVo memberVo) throws Exception{
		BaseQueryVo vo   = new BaseQueryVo();
		memberVo.setPassword(null);//防止修改密码
		if (!checkLogin(memberVo)){
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		try {
			Member member = memberService.get(memberVo.getMemberId());
			ObjcetCopy.copyPropertiesIgnoreNull(memberVo,member);
			memberService.save(member);
		}catch (Exception e){
			logger.error(e.getMessage());
			return returnMsgAPIService.getRet(Constants.saveError);
		}
		return  returnMsgAPIService.getRet(Constants.ok);
	}
	@ResponseBody
	@RequestMapping(value = "/getUserInfo" , method = RequestMethod.POST)
	public BaseQueryVo getUserInfo(HttpServletRequest request,MemberVo vo) throws Exception{
		if (!checkLogin(vo)){
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		try {
			MemberVo memberVo = new MemberVo();
			memberVo.setRetCode(0);
			memberVo.setRetMsg("查询成功");
			CustomMemberVO customMemberVO = new CustomMemberVO();
			Member member = memberService.get(vo.getMemberId());//查询用户基本信息
			if (member != null){
				ObjcetCopy.copyPropertiesIgnoreNull(member,vo);
				if (StringUtils.isNotEmpty(member.getOpenId())){
					vo.setOpenId("1");
				}else {
					vo.setOpenId("0");
				}
				if (StringUtils.isNotEmpty(member.getUnionId())){
					vo.setUnionId("1");
				}else {
					vo.setUnionId("0");
				}
				customMemberVO.setMember(vo);
			}
			List<Tag> listTag =  tagAPIService.selectTagsByMember(member);
			if (listTag != null){
				customMemberVO.setTags(listTag);
			}
			Integer loanCount = loanListService.getMemberLoanCount(vo.getMemberId());
			customMemberVO.setLoanCount(loanCount); //申请记录数量

			Double loanSum = loanListService.getMemberLoanSum(vo.getMemberId());
			customMemberVO.setLoanMoney(loanSum); //申请记录数量
			memberVo.setData(customMemberVO);
			return memberVo;
		}catch (Exception e){
			logger.error(e.getMessage());
			return returnMsgAPIService.getRet(Constants.saveError);
		}
	}
	@ResponseBody
	@RequestMapping(value = "/getAllTags" , method = RequestMethod.POST)
	public BaseQueryVo getAllTags(HttpServletRequest request,MemberVo vo) throws Exception{
	/*	if (!checkLogin(vo)){
			return returnMsgAPIService.getRet(Constants.errLogin);
		}*/
		try {
			BaseQueryVo baseQueryVo = new BaseQueryVo();
			baseQueryVo.setRetCode(0);
			baseQueryVo.setRetMsg("查询成功");
			List<Tag> listTag =  tagAPIService.selectAllTags();
			if (listTag != null){
				baseQueryVo.setData(listTag);
			}
			return baseQueryVo;
		}catch (Exception e){
			logger.error(e.getMessage());
			return returnMsgAPIService.getRet(Constants.saveError);
		}
	}
	@ResponseBody
	@RequestMapping(value = "/updateTags" , method = RequestMethod.POST)
	public BaseQueryVo updateTags(HttpServletRequest request,MemberVo vo) throws Exception{
		if (!checkLogin(vo)){
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		try {
			BaseQueryVo baseQueryVo = new BaseQueryVo();
			baseQueryVo.setRetCode(0);
			baseQueryVo.setRetMsg("修改成功");
			List<MemberTag> memberTags = new Gson().fromJson(vo.getTags(), new TypeToken<List<MemberTag>>(){}.getType());
			if (memberTags != null && memberTags.size() > 0){

				List<MemberTag> saveTags = new ArrayList<MemberTag>();
				for (MemberTag tag : memberTags){
					tag.setId(IdGen.uuid());
					tag.setMemberId(vo.getMemberId());
					tag.setTagId(tag.getTagId());
					saveTags.add(tag);
				}
				vo.setListTags(saveTags);
				tagAPIService.deleteByMemberId(vo.getMemberId());
				int ret =  tagAPIService.updateMemberTags(vo);
			}else {
				return  returnMsgAPIService.getRet(Constants.blankTags);
			}
			return baseQueryVo;
		}catch (Exception e){
			logger.error(e.getMessage());
			return returnMsgAPIService.getRet(Constants.saveError);
		}
	}
	@ResponseBody
	@RequestMapping(value = "/updatePassword" , method = RequestMethod.POST)
	public BaseQueryVo updatePassword(HttpServletRequest request,MemberVo memberVo) throws Exception{
		try {
			BaseQueryVo baseQueryVo = new BaseQueryVo();
			baseQueryVo.setRetCode(0);
			baseQueryVo.setRetMsg("修改成功");

			//检查号码与验证码是否匹配
			ValiCode rightValiCode = valiCodeAPIService.selectLastValiCode(memberVo.getTelephone(), memberVo.getValiCode());
			if (rightValiCode == null) {
				//将错误信息记录到registErrorMap中
				TreeSet<Date> set = null;
				if (registErrorMap.containsKey(memberVo.getTelephone())) {
					set = registErrorMap.get(memberVo.getTelephone());
				} else {
					set = new TreeSet<Date>();
				}
				set.add(new Date());
				registErrorMap.put(memberVo.getTelephone(), set);
				//剩余机会
				int remainTimes = 4;
				if (registErrorMap.containsKey(memberVo.getTelephone())) {
					remainTimes -= registErrorMap.get(memberVo.getTelephone()).size();
				}
				baseQueryVo.setRetCode(100);
				if (remainTimes > 0) {
					baseQueryVo.setRetMsg("验证码错误，您还有" + remainTimes + "次机会");
				} else {
					baseQueryVo.setRetMsg("1分钟内错误次数太多，请稍候再试");
				}
				return baseQueryVo;
			} else if (System.currentTimeMillis() - rightValiCode.getSentTime().getTime() > 2 * 60 * 1000) {
				//验证码超时
				baseQueryVo.setRetCode(100);
				baseQueryVo.setRetMsg("验证码超时，请重新发送");
				return baseQueryVo;
			}
			Member member = memberAPIService.getMemberByPhoneNum(memberVo.getTelephone());
			if (member == null){
				return returnMsgAPIService.getRet(Constants.errUserNameorPassword);
			}else {
				if (memberVo.getPassword() == null || memberVo.getPassword().equals("")){
					return returnMsgAPIService.getRet(Constants.incompleteData);
				}
				member.setPassword(MD5Utils.getMd5Password(memberVo.getPassword(),memberVo.getPassword()));
				member.setSessionId(UUIDUtils.getUUID()); //刷新session
				//baseQueryVo.setSessionId(member.getSessionId());
				if (!com.server.common.utils.StringUtils.isEmpty(member.getSessionId())){
					JedisUtils.set(member.getId(),member.getSessionId(),0);
				}
				memberService.save(member);
			}
			return baseQueryVo;
		}catch (Exception e){
			logger.error(e.getMessage());
			return returnMsgAPIService.getRet(Constants.saveError);
		}
	}

	@ResponseBody
	@RequestMapping(value = "/bind3Login", method = RequestMethod.POST)
	public BaseQueryVo bind3Login(HttpServletRequest request,BaseQueryVo baseQueryVo) throws Exception {
		if (!checkLogin(baseQueryVo)) {
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		Member member = memberService.get(baseQueryVo.getMemberId());
		if (member == null) {
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		if (StringUtils.isNotEmpty(baseQueryVo.getOptType())) {
			if (StringUtils.isNotEmpty(baseQueryVo.getObjId())) {
				if (baseQueryVo.getOptType().equals("wx")) {
					member.setUnionId(baseQueryVo.getObjId());
					member.setAccessToken(baseQueryVo.getAccessToken());
					Member tmpMember = memberAPIService.getMemberByUnionId(member);
					if (tmpMember != null){
						return returnMsgAPIService.getRet(Constants.bindWxError);
					}
				} else if (baseQueryVo.getOptType().equals("qq")) {
					//暂时不处理QQ的绑定登陆
					return returnMsgAPIService.getRet(Constants.incompleteData);
				//	member.setOpenId(baseQueryVo.getObjId());
				}else  return returnMsgAPIService.getRet(Constants.incompleteData);

				memberService.save(member);
				baseQueryVo.setRetCode(0);
				baseQueryVo.setRetMsg("绑定成功");
				return baseQueryVo;
			} else {
				return returnMsgAPIService.getRet(Constants.incompleteData);
			}
		} else return returnMsgAPIService.getRet(Constants.incompleteData);
	}

	@ResponseBody
	@RequestMapping(value = "/check3Login", method = RequestMethod.POST)
	public BaseQueryVo check3Login(HttpServletRequest request,BaseQueryVo baseQueryVo) throws Exception {
		if (!checkLogin(baseQueryVo)) {
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		Member member = memberService.get(baseQueryVo.getMemberId());
		if (member == null) {
			return returnMsgAPIService.getRet(Constants.errLogin);
		}
		if (StringUtils.isNotEmpty(baseQueryVo.getOptType()) && baseQueryVo.getOptType().equals("wx")) {
				if (wxService.checkToken(baseQueryVo.getAccessToken(), baseQueryVo.getObjId())) {
					baseQueryVo.setRetCode(0);
					baseQueryVo.setRetMsg("账户未失效");
				} else {
					return returnMsgAPIService.getRet(Constants.errLogin);
				}
			} else {
				return returnMsgAPIService.getRet(Constants.incompleteData);
			}
		return baseQueryVo;
	}

	@ResponseBody
	@RequestMapping(value = "/findtel")
	public Boolean findtel(String meberphone){
		String tel = memberService.findtel1(meberphone);
		BaseQueryVo baseQueryVo = new BaseQueryVo();
		baseQueryVo.setRetCode(0);
		baseQueryVo.setRetMsg("数据合法");
		if(tel == null){
			return true;
		}
	return false;
	}

}
